package com.fire.security.controller;

import com.fire.security.core.text.FireSecurityConstants;
import com.fire.security.domain.CurrentUser;
import com.fire.security.domain.Result;
import com.fire.security.domain.User;
import com.fire.security.service.UserService;
import com.fire.security.utils.MD5Util;
import com.fire.security.utils.TokenUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {


	//注入UserService
	@Autowired
	private UserService userService;

	//注入redis模板
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	//注入TokenUtils
	@Autowired
	private TokenUtils tokenUtils;

	//登录的url接口/login
	@PostMapping("/login")
	public Result login(CurrentUser currentUser, String code) {
		//校验验证码：
		if(!stringRedisTemplate.hasKey(code)){
			return Result.err(Result.CODE_ERR_BUSINESS, "验证码不正确！");
		}
		//根据用户名查询用户
		CurrentUser user = userService.findByName(currentUser.getName());

		return getResult(currentUser, user);
	}
	//获取当前登录用户信息的url接口/curr-user
	@GetMapping("/curr-user")
	public Result currUser(@RequestHeader(FireSecurityConstants.HEADER_TOKEN_NAME) String clientToken) {
		User currentUser = tokenUtils.getCurrentUser(clientToken);
		return Result.ok(currentUser);
	}

	@DeleteMapping("/logout")
	public Result logout(String clientToken) {
		stringRedisTemplate.delete(clientToken);
		return Result.ok();
	}
	//登录的url接口/login
	@PostMapping("/user/login")
	public Result UserLogin( CurrentUser currentUser,String code) {
		//校验验证码：
		if(!stringRedisTemplate.hasKey(code)){
			return Result.err(Result.CODE_ERR_BUSINESS, "验证码不正确！");
		}
		stringRedisTemplate.delete(code);
		//根据用户名查询用户
		CurrentUser user = userService.findUserByName(currentUser.getName());
		return getResult(currentUser, user);
	}

	private Result getResult(CurrentUser currentUser, CurrentUser user) {
		if (user!=null) {
			String password = MD5Util.hmacSign(currentUser.getPassword());
			if (password.equals(user.getPassword())) {
				String token = tokenUtils.loginSign(user, user.getPassword());
				return Result.ok("登录成功！", token);
			} else {
				return Result.err(Result.CODE_ERR_BUSINESS, "密码不正确！");
			}
		}else{
			return Result.err(Result.CODE_ERR_BUSINESS, "该用户不存在！");
		}
	}
}
